Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

String basics

String intro

In Java, a String is a sequence of characters. It is an object that represents a sequence of char values. Unlike primitive data types, String is not a keyword in Java, but a predefined class in the Java library, just like System or Scanner. Here are some key points about String in Java: Immutable: Once a String object is created, it cannot be changed. This is because of the immutability feature in Java. If you try to alter their values, another object gets created, instead of changing the value of the existing object.
Immutable String s1 = ""Hello""; s1 = s1 + ""World""; // A new object is created in this line
String Literal vs New Keyword: String objects can be created either by using the new keyword or by using String literals.
String Literal vs New Keyword String s1 = ""Hello""; // String Literal String s2 = new String(""Hello""); // Using 'new' keyword
String Pool: The String pool (also known as the intern pool) is a special memory region where Strings are stored by the JVM. When you create a String object using a string literal, the JVM checks the String pool. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object initializes, and places in the pool. String Methods: String class provides a lot of methods to perform operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc. Concatenation: The String class includes the + and += operators to concatenate strings.
Concatenation String s = ""Hello ""; s += ""World"";
Comparison: You can compare strings using the equals() method or the == operator. The equals() method compares the “value” of string for equality. The == operator compares whether two references point to the same object, not their values.
Java String Comparison String s1 = ""Hello""; String s2 = new String(""Hello""); System.out.println(s1 == s2); // false System.out.println(s1.equals(s2)); // true
Remember, String is one of the most important classes in Java. It’s used in almost every application. Understanding how to use it is a critical skill for any Java programmer.

  📌TAGS

★String ★java ★string methods ★ concatenation

Tutorials